package com.yy.chapter6.controller;

import com.yy.chapter6.vo.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Locale;

/**
 * @author yangyao
 * @Description: ValidateController
 * @date 2018/10/23 09:37
 */
@RestController
public class ValidateController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping(value = "/valid")
    public String validMsg(@Valid Test test, BindingResult result) {
        if (result.hasErrors()) {
            StringBuilder stringBuffer = new StringBuilder();
            List<FieldError> fieldErrors = result.getFieldErrors();
            Locale locale = LocaleContextHolder.getLocale();
            for (FieldError fieldError : fieldErrors) {
                String errorMsg = messageSource.getMessage(fieldError, locale);
                stringBuffer.append(fieldError.getField()).append(":").append(errorMsg);
            }
            return stringBuffer.toString();
        }
        return "验证通过";
    }
}
